package com.ruoyi.fun.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.fun.domain.EcProduct;
import com.ruoyi.fun.service.IEcProductService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 商品Controller
 * 
 * @author ruoyi
 * @date 2025-08-06
 */
@RestController
@RequestMapping("/fun/product")
public class EcProductController extends BaseController
{
    @Autowired
    private IEcProductService ecProductService;

    /**
     * 查询商品列表
     */
    @PreAuthorize("@ss.hasPermi('fun:product:list')")
    @GetMapping("/list")
    public TableDataInfo list(EcProduct ecProduct)
    {
        startPage();
        Long orgId = getOrgId();
        // 103组织拥有不过滤的权限
        if (orgId != null && orgId == 103L) {
            orgId = null;
        }
        System.out.println("[商品列表查询] 当前用户orgId: " + orgId);
        ecProduct.setOrgId(orgId);
        List<EcProduct> list = ecProductService.selectEcProductList(ecProduct);
        System.out.println("[商品列表查询] 查询结果数量: " + (list != null ? list.size() : 0));
        return getDataTable(list);
    }

    /**
     * 导出商品列表
     */
    @PreAuthorize("@ss.hasPermi('fun:product:export')")
    @Log(title = "商品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EcProduct ecProduct)
    {
        Long orgId = getOrgId();
        // 103组织拥有不过滤的权限
        if (orgId != null && orgId == 103L) {
            orgId = null;
        }
        ecProduct.setOrgId(orgId);
        List<EcProduct> list = ecProductService.selectEcProductList(ecProduct);
        ExcelUtil<EcProduct> util = new ExcelUtil<EcProduct>(EcProduct.class);
        util.exportExcel(response, list, "商品数据");
    }

    /**
     * 获取商品详细信息
     */
    @PreAuthorize("@ss.hasPermi('fun:product:query')")
    @GetMapping(value = "/{productId}")
    public AjaxResult getInfo(@PathVariable("productId") Long productId)
    {
        Long orgId = getOrgId();
        // 103组织拥有不过滤的权限
        if (orgId != null && orgId == 103L) {
            orgId = null;
        }
        return success(ecProductService.selectEcProductByProductIdAndOrgId(productId, orgId));
    }

    /**
     * 新增商品
     */
    @PreAuthorize("@ss.hasPermi('fun:product:add')")
    @Log(title = "商品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EcProduct ecProduct)
    {
        ecProduct.setOrgId(getOrgId());
        return toAjax(ecProductService.insertEcProduct(ecProduct));
    }

    /**
     * 修改商品
     */
    @PreAuthorize("@ss.hasPermi('fun:product:edit')")
    @Log(title = "商品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EcProduct ecProduct)
    {
        return toAjax(ecProductService.updateEcProduct(ecProduct));
    }

    /**
     * 删除商品
     */
    @PreAuthorize("@ss.hasPermi('fun:product:remove')")
    @Log(title = "商品", businessType = BusinessType.DELETE)
	@DeleteMapping("/{productIds}")
    public AjaxResult remove(@PathVariable Long[] productIds)
    {
        Long orgId = getOrgId();
        return toAjax(ecProductService.deleteEcProductByProductIds(productIds, orgId));
    }

    /**
     * 查询热销商品列表
     */
    @PreAuthorize("@ss.hasPermi('fun:product:list')")
    @GetMapping("/hot")
    public TableDataInfo getHotProducts(EcProduct ecProduct)
    {
        // 设置热销商品查询条件
        ecProduct.setIsHot("1");
        ecProduct.setPublishStatus("1");
        ecProduct.setStatus("0");
        
        startPage();
        List<EcProduct> list = ecProductService.selectEcProductList(ecProduct);
        return getDataTable(list);
    }

    /**
     * 查询推荐商品列表
     */
    @PreAuthorize("@ss.hasPermi('fun:product:list')")
    @GetMapping("/recommend")
    public TableDataInfo getRecommendProducts(EcProduct ecProduct)
    {
        // 设置推荐商品查询条件
        ecProduct.setIsRecommend("1");
        ecProduct.setPublishStatus("1");
        ecProduct.setStatus("0");
        
        startPage();
        List<EcProduct> list = ecProductService.selectEcProductList(ecProduct);
        return getDataTable(list);
    }

    /**
     * 查询新品商品列表
     */
    @PreAuthorize("@ss.hasPermi('fun:product:list')")
    @GetMapping("/new")
    public TableDataInfo getNewProducts(EcProduct ecProduct)
    {
        // 设置新品商品查询条件
        ecProduct.setIsNew("1");
        ecProduct.setPublishStatus("1");
        ecProduct.setStatus("0");
        
        startPage();
        List<EcProduct> list = ecProductService.selectEcProductList(ecProduct);
        return getDataTable(list);
    }
    /**
     * 根据productId和组织ID获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('fun:ecproduct:query')")
    @GetMapping(value = "/{productId}/org/{orgId}")
    public AjaxResult getInfoByOrgId(@PathVariable("productId") Long productId, @PathVariable("orgId") Long orgId)
    {
        return success(ecProductService.selectEcProductByProductIdAndOrgId(productId, orgId));
    }

    /**
     * 根据组织ID查询列表
     */
    @PreAuthorize("@ss.hasPermi('fun:ecproduct:list')")
    @GetMapping("/org/{orgId}")
    public TableDataInfo listByOrgId(@PathVariable Long orgId)
    {
        startPage();
        EcProduct ecProduct = new EcProduct();
        List<EcProduct> list = ecProductService.selectEcProductListByOrgId(ecProduct, orgId);
        return getDataTable(list);
    }

    /**
     * 导入商品数据
     */
    @Log(title = "商品", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file, @RequestParam(value = "updateSupport", defaultValue = "false") boolean updateSupport) throws Exception
    {
        ExcelUtil<EcProduct> util = new ExcelUtil<EcProduct>(EcProduct.class);
        List<EcProduct> productList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        Long orgId = getOrgId();
        String message = ecProductService.importProduct(productList, updateSupport, operName, orgId);
        return success(message);
    }

    /**
     * 下载导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException
    {
        ExcelUtil<EcProduct> util = new ExcelUtil<EcProduct>(EcProduct.class);
        util.importTemplateExcel(response, "商品数据");
    }

    /**
     * 更新商品销量
     */
    @Log(title = "更新商品销量", businessType = BusinessType.UPDATE)
    @PostMapping("/updateSaleCount/{productId}")
    public AjaxResult updateSaleCount(@PathVariable("productId") Long productId)
    {
        try {
            ecProductService.updateProductSaleCount(productId, 1);
            return AjaxResult.success("商品销量更新成功");
        } catch (Exception e) {
            logger.error("更新商品销量失败：" + e.getMessage(), e);
            return AjaxResult.error("更新商品销量失败：" + e.getMessage());
        }
    }

}

